package easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
@Slf4j
public class ZhangsanDemoAnalysisDataListener extends DemoDataListener {

    private Map<Integer, String> headMap;

    public ZhangsanDemoAnalysisDataListener(int headRowNumber) {
        super(headRowNumber);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        if (this.headMap == null) {
            this.headMap = ConverterUtils.convertToStringMap(headMap, context);
        }
    }

    public Map<Integer, String> getHeadMap() {
        return headMap;
    }

    private static final Pattern pattern = Pattern.compile("(\\d+)人?");
    private static final Pattern pattern2 = Pattern.compile("共?(\\d+)人?");

    @Override
    public List<Map<Integer, String>> getDataList() {
        int columnSize = headMap.size(); // 14
        for (Map<Integer, String> integerStringMap : dataList) {
            String sceneryName = integerStringMap.get(0);
            String totalCountStr = integerStringMap.get(1);
            if (sceneryName != null && !sceneryName.isEmpty()) {
                if (totalCountStr == null || totalCountStr.isEmpty()) {
                    throw new RuntimeException("人数字段不能为空");
                }
                Matcher matcher = pattern.matcher(totalCountStr);
                if (!matcher.matches()) {
                    throw new RuntimeException("总人数字段校验失败");
                }
                int allCount = Integer.parseInt(matcher.group(1));

                String personCount;
                String visitContent;
                // col=2 是日期, col=3 是内容; col=4 是日期, col=5 是内容 ...
                for (int i = 2; i < columnSize; i += 2) {
                    visitContent = integerStringMap.get(i);
                    personCount = integerStringMap.get(i + 1);
                    if (visitContent == null && personCount == null) {
                        continue;
                    }
                    matcher = pattern2.matcher(personCount);
                    if (!matcher.matches()) {
                        throw new RuntimeException("人数字段校验失败");
                    }
                    // 更新 personCount
                    personCount = matcher.group(1);
                    String visitDate = headMap.get(i);
                    System.out.println("景点名称 = "+sceneryName+", 所有人数 = "+allCount+", 日期 = " + visitDate+", 人数 = "+personCount
                            +", 安排 = " + visitContent);
                }
            }
        }
        return dataList;
    }

}